<template>
    <!-- 面包屑导航区域 -->
    <div>
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!-- 卡片视图区域 -->
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-button v-if="hasPermission('添加分类功能')" type="primary" @click="addDialogVisible = true">添加分类</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="catelist" stripe border style="width: 100%; height: 100%" class="user-table" fit row-key="cat_id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">    
                <el-table-column type="index" label="#" width="50" fixed="left" />
                <el-table-column prop="cat_name" label="分类名称" min-width="20" fixed="left">
                    <template #default="scope">
                        <div class="category-name">
                            <span>{{ scope.row.cat_name }}</span>
                            <!-- <el-tag size="small" type="info" class="goods-count">{{ (scope.row.goods || []).length }}个商品</el-tag> -->
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="cat_deleted" label="是否有效" width="80">
                    <template #default="scope">
                        <el-tag :type="!scope.row.cat_deleted ? 'success' : 'danger'" size="small">
                            {{ !scope.row.cat_deleted ? '有效' : '无效' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="cat_level" label="排序" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.cat_level === 0 ? '' : scope.row.cat_level === 1 ? 'success' : 'warning'" size="small">
                            {{ scope.row.cat_level === 0 ? '一级' : scope.row.cat_level === 1 ? '二级' : '三级' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" show-overflow-tooltip>
                    <template #default="scope">
                        <div class="description-content" v-tooltip="{ content: scope.row.description || '暂无描述', effect: 'dark', placement: 'top', enterable: false, hideAfter: 20, showAfter: 20 }">
                            {{ scope.row.description || '暂无描述' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="scope">
                        <div class="operation-buttons">
                            <el-button v-if="hasPermission('编辑分类功能')" type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button v-if="hasPermission('删除分类功能')" type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row.cat_id)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
                :page-sizes="[1, 8, 16, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加分类的对话框 -->
        <el-dialog v-model="addDialogVisible" title="添加分类" width="50%" @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="addForm.cat_name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="父级分类" prop="cat_pid">
                    <el-cascader
                        v-model="selectedKeys"
                        :options="parentCateList"
                        :props="cascaderProps"
                        @change="parentCateChanged"
                        clearable
                    ></el-cascader>
                </el-form-item> -->
                <el-form-item label="描述" prop="description">
                    <el-input v-model="addForm.description" type="textarea" :rows="3"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="addForm.status" placeholder="请选择状态">
                        <el-option label="启用" value="enabled"></el-option>
                        <el-option label="禁用" value="disabled"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addCate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 修改分类的对话框 -->
        <el-dialog v-model="editDialogVisible" title="修改分类" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="editForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="editForm.description" type="textarea" :rows="3"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="editForm.status" placeholder="请选择状态">
                        <el-option label="启用" value="enabled"></el-option>
                        <el-option label="禁用" value="disabled"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editCate">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ArrowRight, Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "@/utils/http"
import { debounce } from 'lodash'

// 添加权限检查函数
const hasPermission = (permission) => {
    const userFunctions = JSON.parse(sessionStorage.getItem('permissions') || '[]')
    return userFunctions.includes(permission)
}

const catelist = ref([])
const queryInfo = ref({
    type: 3,
    pagenum: 1,
    pagesize: 8
})
const total = ref(0)

// 获取商品分类列表
const getCateList = async () => {
    const { data: res } = await axios.get('/api/products/', {
        params: {
            type: queryInfo.value.type,
            page: queryInfo.value.pagenum,
            page_size: queryInfo.value.pagesize
        }
    })
    console.log("获取的数据是:",res)
    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }
    
    // 处理分类数据，添加商品信息
    const categories = res.data.categories || []
    const products = res.data.list || []
    
    // 创建商品ID到商品信息的映射
    const productMap = new Map(products.map(product => [product.id, product]))
    
    // 为每个分类统计所有商品
    const categoryProducts = new Map()
    products.forEach(product => {
        const categoryId = product.category_id
        if (!categoryProducts.has(categoryId)) {
            categoryProducts.set(categoryId, [])
        }
        categoryProducts.get(categoryId).push(product)
    })
    
    const processedCategories = categories.map(category => ({
        cat_id: category.id,
        cat_name: category.name,
        cat_pid: category.parent_category || 0,
        cat_level: category.level === '一级' ? 0 : category.level === '二级' ? 1 : 2,
        cat_deleted: category.status !== 'enabled',
        description: category.description,
        goods: (categoryProducts.get(category.id) || []).map(product => ({
            id: product.id,
            name: product.name,
            price: product.price,
            stock: product.stock,
            status: product.status,
            description: product.description
        }))
    }))
    
    // 设置总数据量
    total.value = processedCategories.length
    
    // 分页处理
    const startIndex = (queryInfo.value.pagenum - 1) * queryInfo.value.pagesize
    const endIndex = startIndex + queryInfo.value.pagesize
    catelist.value = processedCategories.slice(startIndex, endIndex)
}

// 监听 pagesize 改变
const handleSizeChange = (newSize) => {
    queryInfo.value.pagesize = newSize
    getCateList()
}

// 监听页码值改变
const handleCurrentChange = (newPage) => {
    queryInfo.value.pagenum = newPage
    getCateList()
}

// 添加分类相关数据
const addDialogVisible = ref(false)
const addForm = ref({
    cat_name: '',
    cat_pid: 0,
    cat_level: 0,
    description: '',
    status: 'enabled'
})

const addFormRules = {
    cat_name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
    ],
    description: [
        { required: false, message: '请输入分类描述', trigger: 'blur' }
    ]
}
const addFormRef = ref()
const parentCateList = ref([])
const selectedKeys = ref([])
const cascaderProps = {
    value: 'cat_id',
    label: 'cat_name',
    children: 'children'
}

// 获取父级分类列表
const getParentCateList = async () => {
    const { data: res } = await axios.get('/api/categories/', {
        params: { type: 2 }
    })
    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }
    // 确保返回的数据是数组
    const categories = Array.isArray(res.data) ? res.data : []
    // 处理分类数据格式
    parentCateList.value = categories.map(category => ({
        cat_id: category.id,
        cat_name: category.name,
        cat_level: category.level === '一级' ? 0 : category.level === '二级' ? 1 : 2,
        children: category.children ? category.children.map(child => ({
            cat_id: child.id,
            cat_name: child.name,
            cat_level: child.level === '一级' ? 0 : child.level === '二级' ? 1 : 2
        })) : []
    }))
}

// 选择项发生变化
const parentCateChanged = () => {
    if (selectedKeys.value.length > 0) {
        addForm.value.cat_pid = selectedKeys.value[selectedKeys.value.length - 1]
        addForm.value.cat_level = selectedKeys.value.length
    } else {
        addForm.value.cat_pid = 0
        addForm.value.cat_level = 0
    }
}

// 点击按钮添加分类
const addCate = async () => {
    const valid = await addFormRef.value.validate()
    if (!valid) return

    const formData = new URLSearchParams()
    formData.append('name', addForm.value.cat_name)
    if (addForm.value.cat_pid !== 0) {
        formData.append('parent_category_id', addForm.value.cat_pid)
    }
    formData.append('description', addForm.value.description)
    formData.append('status', addForm.value.status)

    const { data: res } = await axios.post('api/categories/add/', formData, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })

    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }

    ElMessage.success('添加分类成功')
    addDialogVisible.value = false
    getCateList()
}

// 关闭添加分类对话框
const addDialogClosed = () => {
    addFormRef.value.resetFields()
    selectedKeys.value = []
    addForm.value.cat_pid = 0
    addForm.value.cat_level = 0
    addForm.value.description = ''
    addForm.value.status = 'enabled'
}

// 编辑分类相关数据
const editDialogVisible = ref(false)
const editForm = ref({
    cat_id: 0,
    cat_name: '',
    description: '',
    status: 'enabled'
})
const editFormRef = ref()
const editFormRules = {
    cat_name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
    ],
    description: [
        { required: false, message: '请输入分类描述', trigger: 'blur' }
    ]
}

// 展示编辑分类对话框
const handleEdit = (row) => {
    editForm.value = {
        cat_id: row.cat_id,
        cat_name: row.cat_name,
        description: row.description || '',
        status: row.cat_deleted ? 'disabled' : 'enabled'
    }
    editDialogVisible.value = true
}

// 修改分类
const editCate = async () => {
    const valid = await editFormRef.value.validate()
    if (!valid) return

    const requestData = {
        name: editForm.value.cat_name,
        description: editForm.value.description,
        status: editForm.value.status
    }

    const { data: res } = await axios.put(`/api/edit-category/${editForm.value.cat_id}/`, requestData, {
        headers: {
            'Content-Type': 'application/json'
        }
    })

    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }

    ElMessage.success('更新分类成功')
    editDialogVisible.value = false
    getCateList()
}

// 关闭编辑分类对话框
const editDialogClosed = () => {
    editFormRef.value.resetFields()
}

// 删除分类
const handleDelete = async (id) => {
    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(err => err)

    if (confirmResult !== 'confirm') {
        return ElMessage.info('已取消删除')
    }
    console.log("id:",id)
    const { data: res } = await axios.delete(`/api/categories/delete/${id}/`)
    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }

    ElMessage.success('删除分类成功')
    getCateList()
}

onMounted(() => {
    getCateList()
    getParentCateList()
})
</script>

<style scoped>
.user-table {
    max-width: 100%;
    overflow-x: auto;
    height: calc(100vh - 250px);
    margin: 20px 0;
}

.el-table {
    height: 100%;
}

.operation-buttons {
    display: flex;
    gap: 16px;
    justify-content: center;
}

.operation-buttons .el-button {
    margin: 0;
    padding: 4px 12px;
    font-size: 12px;
}

/* 添加新的样式规则 */
.el-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    padding: 8px 16px;
}

.el-button [class*='el-icon'] + span {
    margin-left: 4px;
}
.category-name {
    display: flex;
    align-items: center;
    gap: 8px;
}

.goods-count {
    font-size: 11px;
}

.description-content {
    color: #606266;
    font-size: 13px;
    cursor: pointer;
}

:deep(.el-tooltip__popper) {
    max-width: 300px;
    line-height: 1.5;
    padding: 8px 12px;
    transition: all 0.15s ease-in-out;
    opacity: 0;
}

:deep(.el-tooltip__popper[data-show]) {
    opacity: 1;
}
.expanded-content {
    padding: 16px;
    background-color: #f8f9fa;
}

.price-tag {
    color: #f56c6c;
    font-weight: 500;
}

.role-assignment-dialog :deep(.el-dialog__body) {
    padding: 20px 30px;
}

.role-info {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-item .label {
    width: 100px;
    color: #606266;
    font-weight: 500;
}

.info-item .value {
    flex: 1;
}

.role-select {
    width: 300px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
}
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>
